package model

import (
	"context"
	"github.com/LyricTian/gin-admin/v7/internal/app/contextx"
	"github.com/LyricTian/gin-admin/v7/internal/app/model/gormx/entity"
	"github.com/LyricTian/gin-admin/v7/internal/app/schema"
	"github.com/LyricTian/gin-admin/v7/pkg/errors"
)

//  每个人只能读取自己的群

// Query 查询数据
func (a *Group) GetMyGroup(ctx context.Context, params schema.GroupQueryParam, opts ...schema.GroupQueryOptions) (*schema.GroupQueryResult, error) {
	userId, ok := contextx.FromUserID(ctx)
	if !ok {
		return nil, errors.ErrInvalidUser
	}

	//读取群关联的视频
	//group_id := ""
	//err := entity.GetGroupMemberDB(ctx, a.DB).
	//	Select("group_id").
	//	Where("user_id = ?", userId).Row().Scan(&group_id)
	//if group_id == "" {
	//	return nil, nil
	//}

	subQuery:=entity.GetGroupMemberDB(ctx,a.DB).Select("group_id").Where("user_id = ?",userId).SubQuery()


	//查找标签
	//subQuery := entity.GetGroupDB(ctx, a.DB).Select("tag").Where("id = ?", group_id).SubQuery()
	db := entity.GetGroupDB(ctx, a.DB).Where("id IN ?", subQuery)

	//db := entity.GetGroupDB(ctx, a.DB).Where("tag IN ?", subQuery)
//GetSqlX(a.DB)
	opt := a.getQueryOption(opts...)
	opt.OrderFields = append(opt.OrderFields, schema.NewOrderField("id", schema.OrderByDESC))
	db = db.Order(ParseOrder(opt.OrderFields))

	var list entity.Groups
	pr, err := WrapPageQuery(ctx, db, params.PaginationParam, &list)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	qr := &schema.GroupQueryResult{
		PageResult: pr,
		Data:       list.ToSchemaGroups(),
	}

	return qr, nil
}
